package 字符串.验证IP地址;

public class Solution {
    public static void main(String[] args) {
        System.out.println(solve("172.16.254.1"));
        System.out.println(solve("2001:0db8:85a3:0:0:8A2E:0370:7334"));
        System.out.println(solve("256.256.256.256"));
        System.out.println(solve("2001:00db8:85a3:0:0000:8A2E:0370:7334"));
    }

    public static String solve (String IP) {
        return validIPv4(IP) ? "IPv4" : (validIPv6(IP) ? "IPv6" : "Neither");
    }

    private static boolean validIPv4(String IP) {
        String[] strs = IP.split("\\.", -1);
        if (strs.length != 4) {
            return false;
        }
        for (String str : strs) {
            if (str.length() > 1 && str.startsWith("0")) {
                return false;
            }
            try {
                int val = Integer.parseInt(str);
                if (val < 0 || val > 255) {
                    return false;
                }
            } catch (NumberFormatException e) {
                return false;
            }
        }
        return true;
    }

    private static boolean validIPv6(String IP) {
        String[] strs = IP.split(":", -1);
        if (strs.length != 8) {
            return false;
        }
        for (String str : strs) {
            if (str.length() > 4 || str.length() == 0) {
                return false;
            }
            try {
                Integer.parseInt(str, 16);
            } catch (NumberFormatException exception) {
                return false;
            }
        }
        return true;
    }

}
